<template>
  <div class="normalMaintenanceStandardDetails h100">
    <editPageNew
      ref="editPage"
      :rightBtnArr="rightBtnArr"
      :creatInfo="creatInfo"
      :stepConfig="stepConfig"
      :moreBtnArr="moreBtnArr"
      :showMore="pageType != 'add'"
      showTopTitle
    >
      <template slot="editPageTitle">
        <i class="el-icon-document TitleImg"></i>
        生产报表
      </template>
      <div class="plan-title">
        <div v-show="!showInput" class="name">
          <span style="color: red"></span>
          <span>{{ titleName }}</span>
          <el-link
            v-show="!unEdit"
            style="font-size: 20px"
            icon="el-icon-edit-outline"
            @click="editTitle"
          ></el-link>
        </div>
        <div v-show="showInput" class="name-input">
          <el-input
            type="text"
            v-model="titleName"
            maxlength="64"
            show-word-limit
            @blur="loseFocus"
            placeholder="请输入名称"
            clearable
            ref="mark"
            ><template slot="prepend">标题</template></el-input
          >
        </div>
      </div>
      <el-collapse v-model="activeNames">
        <el-collapse-item name="1">
          <template slot="title">
            <span class="titleLine"></span>
            基本信息
          </template>
          <editForm
            :formConfig="formConfig"
            ref="editForm"
            :formData="formData"
          >
            <template #uploadFiles>
              <attachFormNew
                :attachSetting="attachSetting"
                :isDelete="true"
                @fileChange="fileChange"
                ref="attachSetting"
                :disabled="unEdit"
              ></attachFormNew> </template
          ></editForm>
        </el-collapse-item>
        <el-collapse-item name="2" v-if="[-1, 1, 2].includes(status)">
          <template slot="title">
            <span class="titleLine"></span>
            审批信息
          </template>
          <workFlow
            :isDetails="pageType == 'details'"
            :currentFlowData="formData"
            ref="workFlow"
            workflowCode="production_report"
            @submitSuccess="workFlowSuccess"
          ></workFlow>
        </el-collapse-item>
      </el-collapse>
    </editPageNew>
    <dialogPublic
      title="提交"
      :show.sync="show"
      @doClose="() => (show = false)"
      :fullscreen="true"
      :noFootBtn="true"
      appendTobody
    >
      <workFlow
        v-if="show"
        :isDetails="pageType == 'query'"
        workflowCode="production_report"
        :currentFlowData="formData"
        ref="workFlow"
        @submitSuccess="workFlowInitSuccess"
      ></workFlow>
    </dialogPublic>
  </div>
</template>
<script>
import {
  getDetailsApi,
  addOrUpdate,
  deleteApi,
} from "@/api/orderManagement/productionReport.js";
export default {
  data() {
    return {
      activeNames: ["1", "2"],
      titleName: "",
      showInput: false,
      hideBtn: false,
      pageType: "",
      status: -2,
      show: false,
      orderStatus: ["DRAFT", "WAIT_REVIEW", "APPROVED"],
      formConfig: {
        labelWidth: "100px",
        itemArr: [
          {
            label: "所属单位",
            prop: "deptName", //多选时，字段要为数组类型
            propArr: "deptArr",
            idsStr: "deptId",
            type: "dept-select", //类型
            option: [],
            multiple: false,
            disabled: false,
            required: true,
            methods: (obj) => {},
            span: 8,
          },
          {
            label: "所属月份",
            prop: "month",
            type: "month",
            span: 8,
            placeholder: "请选择",
            required: true,
          },
          {
            label: "类别",
            prop: "category",
            type: "select",
            span: 8,
            required: true,
            disabled: false,
            selectOption: this.$store.getters.dirtData(
              "order_prod_form_category"
            ),
          },
          {
            label: "备注",
            prop: "remark",
            type: "textarea",
            span: 24,
            rows: 3,
            required: false,
            disabled: false,
          },
          {
            label: "附件",
            prop: "uploadFiles",
            type: "text",
            span: 16,
            required: true,
            placeholder: "请选择要上传的附件",
            disabled: true,
          },
        ],
      },
      //弹出框表单数据
      attachSetting: {
        businessId: "",
      },
      formData: {},
      creatInfo: {},
      moreBtnArr: [
        {
          text: "操作记录",
          methods: () => {
            this.$refs.editPage.showOperate();
          },
        },
      ],
    };
  },
  computed: {
    rightBtnArr() {
      let arr = [
        {
          text: "提交",
          icon: "el-icon-s-promotion",
          hide:
            ["details", "perform", "add"].includes(this.pageType) ||
            [-1, 1, 2].includes(this.status),
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("submit"),
          methods: () => {
            this.show = true;
          },
        },
        {
          text: "保存",
          icon: "el-icon-check",
          hide:
            ["details", "perform"].includes(this.pageType) ||
            [-1, 1, 2].includes(this.status),
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("save"),
          methods: () => {
            this.save();
          },
        },
        {
          text: "删除",
          icon: "el-icon-delete-solid",
          hide:
            ["perform", "details", "add"].includes(this.pageType) ||
            [-1, 1, 2].includes(this.status),
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("delete"),
          methods: () => {
            this.deleteId();
          },
        },
      ];
      return arr;
    },
    stepConfig() {
      let obj = {};
      if (this.status == -1) {
        obj = {
          nowStep: 0, //当前步骤，对应stepItem数组的下标，例如：0-步骤一、1-步骤二
          stepItem: ["已作废"],
        };
      } else {
        obj = {
          nowStep: parseInt(this.status), //当前步骤，对应stepItem数组的下标，例如：0-步骤一、1-步骤二
          stepItem: ["草稿", "待审核", "已审批"],
        };
      }
      return obj;
    },
    unEdit() {
      return ["query", "detail"].includes(this.pageType) || [-1, 1, 2].includes(this.status);
    },
  },
  watch: {
    status: {
      handler(val) {
        if (val > 0 || val == -1) {
          this.formConfig.itemArr.forEach(item => item.disabled = true);
        } else {
          this.formConfig.itemArr.forEach(item => item.disabled = false);
        }
      },
    },
  },
  created() {
    this.init();
  },
  mounted() {},
  methods: {
    init() {
      let { id, pageType } = this.$route.query;
      if (id) {
        this.pageType = this.$store.getters.isBtnAuth("edit")
          ? "edit"
          : "detail";
        this.getDetails(id);
      } else {
        this.pageType = "add";
        this.showInput = true;
      }
    },
    // 预览
    preview() {
      const { href } = this.$router.resolve({
        name: "specialManagementPrint",
        query: {
          id: this.$route.query.id,
          type: this.$route.meta.code,
          pageType: this.$route.query.pageType,
        },
      });
      window.open(href, "_blank");
    },
    //编辑标题
    editTitle() {
      this.showInput = true;
      setTimeout(() => {
        this.$refs.mark.focus();
      }, 0);
    },
    //失去焦点
    loseFocus() {
      if (this.titleName != "") {
        this.showInput = false;
      } else {
        this.$message.warning("名称不能为空");
      }
    },
    //根据项目名称生成标题
    produceTitle(name) {
      this.titleName = name + "_会议纪要";
    },
    //获取标准详情
    getDetails(id) {
      getDetailsApi({ id: id }).then((res) => {
        if (res.code == 200) {
          let data = res.data;
          this.status = data.status;
          this.creatInfo = res.data;
          this.titleName = data.title;
          this.attachSetting.businessId = data.id;
          let orgOption = [
            {
              label: data.deptName,
              value: data.deptId,
            },
          ];
          this.formData = data;
          setTimeout(() => {
            this.$refs.editForm.setItemOption("deptName", orgOption);
            this.$refs.editForm.setFormItem("deptArr", data.deptId);
          }, 0);
        }
      });
    },
    //删除
    deleteId() {
      this.$confirm("确定要删除该条数据吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteApi({ id: this.formData.id }).then((res) => {
            if (res.code === 200) {
              this.$message.success(res.description);
              this.$utils.addOperateLog(this.formData.id, "删除-会议纪要");
              this.updateListData();
              this.$refs.editPage.closePage();
            }
          });
        })
        .catch((e) => {});
    },
    //保存正常维护标准
    async save() {
      try {
        let formData = await this.$refs.editForm.getFormData();
        formData.title = this.titleName;
        //if (this.pageType == "add") {
        formData.status = 0;
        //}
        let res = await addOrUpdate(formData);
        await this.uploadFile(res.data);
        this.$message.success(res.description);
        this.updateListData();
        if (this.pageType == "add") {
          this.$utils.addOperateLog(res.data, "新建-生产报表");
          let obj = {
            id: res.data,
            pageType: "edit",
          };
          this.$router.push({
            query: obj,
          });
        } else {
          this.$utils.addOperateLog(this.formData.id, "修改-生产报表");
          this.getDetails(this.formData.id);
        }
      } catch (error) {}
    },
    /* 更新列表页的数据 */
    updateListData() {
      /* 通过localStorage来实现浏览器不同窗口之间的通信 */
      let num = Math.floor(Math.random() * 1000) + 1; //产生随机数，保证每次的值都不一样
      localStorage.setItem("update", num); //设置localStorage里面的值，保证每次都会触发storage事件
    },
    //附件变更
    async fileChange(files) {
      this.$refs.editForm.setFormItem("uploadFiles", files);
      await this.$refs.editForm.getFormData();
    },
    //上传附件
    uploadFile(id) {
      new Promise((resolve, reject) => {
        this.attachSetting = { businessId: id };
        resolve(this.attachSetting);
      }).then(() => {
        this.$refs.attachSetting.doSubmitFiles();
      });
    },
    //工作流成功后的回调函数
    workFlowSuccess() {
      this.updateListData();
      this.getDetails(this.formData.id);
      this.$refs.workFlow.initIframe();
    },
    //草稿状态工作流提交成功之后
    workFlowInitSuccess() {
      this.show = false;
      this.$utils.addOperateLog(this.formData.id, "提交审核-生产报表");
      this.updateListData();
      this.getDetails(this.formData.id);
    },
  },
};
</script>
<style>
.el-input__inner {
  font-weight: 600;
}
.el-textarea__inner {
  font-weight: 600;
}
</style>
<style lang="less" scoped>
.normalMaintenanceStandardDetails {
  // overflow: hidden;
  background-color: #ffffff;
  .TitleImg {
    margin-right: 2px;
    font-size: 22px;
  }
  .plan-title {
    height: 40px;
    margin: 0 0 10px 0;
    .name {
      font-size: 18px;
      padding: 0 10px;
      height: 40px;
      font-weight: bold;
      line-height: 40px;
      text-align: left;
      padding: 0 10px;
    }
    .name-input {
      width: 400px;
      height: 40px;
      line-height: 40px;
    }
  }
}
</style>